﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DynamicMVVM
{
    [Serializable]
    public class ModelStateDictionary : Dictionary<string, ModelState>
    {
        public bool IsValid { get { return this.Any(x => x.Value.Errors.Count > 0); } }

        public void AddModelError(string key, Exception exception)
        {
            var modelState = ContainsKey(key) ? this[key] : new ModelState();
            modelState.Errors.Add(exception);
        }
        public void AddModelError(string key, string errorMessage)
        {
            ModelState modelState = GetModelState(key);
            modelState.Errors.Add(errorMessage);
        }

        private ModelState GetModelState(string key)
        {
            if (ContainsKey(key))
            {
                return this[key];
            }
            var modelState = new ModelState();
            
            Add(key, modelState);

            return modelState;
        }

        public bool IsValidField(string key)
        {
            return ContainsKey(key) ? this[key].Errors.Any() : true;
        }
    }
}